package com.lucweb.dao.impl;

import com.lucweb.dao.BuyDao;

import com.lucweb.entity.TaskBuy;

import com.lucweb.entity.TaskMaterial;
import org.hibernate.SessionFactory;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Repository("buyDao")
public class BuyDaoImpl implements BuyDao {


    @Resource(name="sessionFactory")
    private SessionFactory sessionFactory;


    @Override
    public List<TaskBuy> buyList(String para) {
        List<TaskBuy> buyList = (List<TaskBuy>) sessionFactory.getCurrentSession().createQuery("FROM TaskBuy where companyName ='"+para+"'").list();

        return buyList;
    }

    @Override
    public void saveOrUpdate(TaskBuy taskBuy) {
        sessionFactory.getCurrentSession().saveOrUpdate(taskBuy);

    }

    @Override
    public TaskBuy getbuyById(int taskId) {
        return (TaskBuy) sessionFactory.getCurrentSession().get(TaskBuy.class, taskId);
    }

    @Override
    public void deletebuy(int taskId) {

        sessionFactory.getCurrentSession().delete(
                sessionFactory.getCurrentSession().get(TaskBuy.class, taskId)
        );
    }

    @Override
    public List<TaskBuy> showBuy() {
        List<TaskBuy> buyList = (List<TaskBuy>) sessionFactory.getCurrentSession().createQuery("FROM TaskBuy ").list();

        return buyList;
    }

    @Override
    public List<TaskMaterial> showMaterial(int taskId) {
        List<TaskMaterial> materialList = (List<TaskMaterial>) sessionFactory.getCurrentSession().createQuery("FROM TaskMaterial " +
                "where buyId ="+taskId).list();
        return materialList;
    }

    @Override
    public void materialsaveOrUpdate(TaskMaterial taskMaterial) {
        sessionFactory.getCurrentSession().saveOrUpdate(taskMaterial);
    }

    @Override
    public TaskMaterial getmaterialById(int materialId) {
        return (TaskMaterial) sessionFactory.getCurrentSession().get(TaskMaterial.class, materialId);
    }

    @Override
    public void deletematerial(int materialId) {
        sessionFactory.getCurrentSession().delete(
                sessionFactory.getCurrentSession().get(TaskMaterial.class, materialId)
        );
    }

    @Override
    public int getmaxId() {
        Integer number = (Integer) sessionFactory.getCurrentSession().createSQLQuery("select auto_increment from " +
                "information_schema.tables where table_schema='firesystem' and table_name='task_buy';")
                .addScalar("auto_increment", StandardBasicTypes.INTEGER).uniqueResult();
        return number;

    }
}
